<template>
  <div class="amap-container">
    <!-- 地图容器 -->
    <div class="map-wrapper">
      <div id="tdtMap" class="map-container"></div>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <button
        @click="toggleDrawingMode"
        :class="['control-btn', { active: isDrawingMode }]"
      >
        {{ isDrawingMode ? "退出绘制" : "开始框选" }}
      </button>
      <button
        @click="clearDrawing"
        class="control-btn clear-btn"
        :disabled="!hasDrawingData"
      >
        清除
      </button>
      <button
        @click="handleSaveArea"
        class="control-btn save-btn"
        :disabled="!hasValidArea || !validPondId || isAreaOverlapping"
      >
        保存区域经纬度
      </button>
    </div>

    <div v-if="isDrawingMode" class="status-tip drawing">
      ✏️ 绘制模式 - 点击地图添加顶点 (已添加: {{ drawingPoints.length }}个)
      <br />
      <small>提示: 至少需要3个点才能完成绘制</small>
      <br />
      <small>提示: 绘制完成后右键退出绘制</small>
    </div>

    <div
      v-if="isAreaOverlapping"
      class="status-tip error"
      :class="{ 'has-zoom-tip': !showFullArea }"
    >
      ⚠️ 当前框选区域与已有虾塘区域重叠，请重新框选！
    </div>

    <div v-if="!showFullArea" class="zoom-tip">
      🔍 当前缩放级别较小，显示虾塘中心点。放大到16级及以上可查看完整区域。
    </div>

    <div v-if="areaCoords.length" class="area-info">
      <h3>📍 区域信息</h3>
      <div class="info-section">
        <p><strong>顶点数量:</strong> {{ areaCoords.length }} 个</p>
        <p>
          <strong>区域面积:</strong>
          {{ areaArea ? areaArea.toFixed(2) : "计算中..." }} 平方米
        </p>

        <div v-if="centerPoint" class="center-point">
          <p><strong>中心点坐标:</strong></p>
          <p class="coord">经度: {{ centerPoint.lng.toFixed(6) }}</p>
          <p class="coord">纬度: {{ centerPoint.lat.toFixed(6) }}</p>
        </div>

        <div class="coordinates-preview">
          <strong>边界坐标:</strong>
          <div class="coords-list">
            <div
              v-for="(point, index) in areaCoords"
              :key="index"
              class="coord-item"
            >
              {{ index + 1 }}. ({{ point.lat.toFixed(6) }},
              {{ point.lng.toFixed(6) }})
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 当前鼠标位置信息 -->
    <div v-if="mousePosition && isDrawingMode" class="mouse-position">
      <strong>鼠标位置:</strong>
      {{ mousePosition.lat.toFixed(6) }}, {{ mousePosition.lng.toFixed(6) }}
      <span class="drawing-hint">- 点击添加顶点</span>
    </div>
  </div>
</template>

<script>
import { ref, watch, nextTick, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  getAllCentralCoordinate,
  getPondAddressDetailByCentral,
  savePondCoordinates,
} from "@/api/pond";

// 天地图密钥配置
const TDT_KEY = "47e432c98f07256aedf6745fdf75886a";

export default {
  name: "PondMap",
  props: {
    pondId: {
      type: [String, Number, null, undefined],
      default: null,
    },
    // 弹窗显示状态
    visible: {
      type: Boolean,
      default: false,
    },
    refreshFlag: {
      type: Number,
      default: 0,
    },
  },
  emits: ["save-success", "save-fail", "close"],
  setup(props, { emit }) {
    // 地图基础配置
    const mapCenter = ref([113.3245, 23.1061]);
    const zoomLevel = ref(15);
    const enableScrollWheel = ref(true);

    // 地图与绘制状态
    let mapInstance = null;
    let currentPolygon = null; // 当前绘制的多边形
    let tempPolyline = null; // 临时线
    let markers = []; // 绘制的点标记
    let existingPolygons = [];
    const isDrawingMode = ref(false);
    const drawingPoints = ref([]); // 绘制中的点
    const areaCoords = ref([]); // 最终的区域坐标
    const areaArea = ref(null);
    const centerPoint = ref(null);
    const mousePosition = ref(null);
    const existingPonds = ref([]);
    const isAreaOverlapping = ref(false); // 标记当前区域是否重叠
    const showFullArea = ref(true);

    // 计算属性
    const hasDrawingData = computed(
      () => drawingPoints.value.length > 0 || areaCoords.value.length > 0
    );
    const hasValidArea = computed(() => areaCoords.value.length >= 3);
    const validPondId = computed(() => {
      return (
        props.pondId !== null &&
        props.pondId !== undefined &&
        props.pondId !== ""
      );
    });

    // 初始化天地图
    const initMap = async () => {
      try {
        if (!window.T) {
          await loadTdtScript();
          await new Promise((resolve) => setTimeout(resolve, 1000));
        }

        if (!window.T || !window.T.Map) {
          throw new Error("天地图API加载不完整");
        }

        const mapContainer = document.getElementById("tdtMap");
        if (!mapContainer) {
          throw new Error("地图容器未找到");
        }

        // 如果地图实例已存在，先销毁
        if (mapInstance) {
          clearAllMapElements();
          mapInstance.destroy();
        }

        // 初始化地图实例
        mapInstance = new window.T.Map("tdtMap");
        mapInstance.centerAndZoom(
          new window.T.LngLat(...mapCenter.value),
          zoomLevel.value
        );

        // 添加控件
        mapInstance.addControl(new window.T.Control.Scale());
        try {
          if (window.T.Control.ToolBar) {
            mapInstance.addControl(
              new window.T.Control.ToolBar({ showZoomNum: true })
            );
          } else if (window.T.Control.Navigation) {
            mapInstance.addControl(new window.T.Control.Navigation());
          }
        } catch (e) {
          console.warn("工具条控件加载失败:", e);
        }
        mapInstance.enableScrollWheelZoom(enableScrollWheel.value);

        // 绑定事件
        bindMapEvents();
        setupMouseEvents();

        // 根据初始缩放级别设置显示模式
        showFullArea.value = zoomLevel.value > 15;
        await fetchExistingPonds();

        ElMessage.success('地图加载完成，点击"开始框选"进行区域绘制');
      } catch (error) {
        console.error("地图初始化失败:", error);
        ElMessage.error(`地图初始化失败: ${error.message}`);
      }
    };

    // 清除所有地图元素
    const clearAllMapElements = () => {
      // 清除标记
      markers.forEach((marker) => {
        try {
          mapInstance.removeOverLay(marker);
        } catch (e) {
          console.warn("移除标记失败:", e);
        }
      });
      markers = [];

      // 清除现有虾塘多边形
      existingPolygons.forEach((polygon) => {
        try {
          mapInstance.removeOverLay(polygon);
        } catch (e) {
          console.warn("移除现有多边形失败:", e);
        }
      });
      existingPolygons = [];

      // 清除当前绘制的多边形和临时线
      if (currentPolygon) {
        try {
          mapInstance.removeOverLay(currentPolygon);
        } catch (e) {
          console.warn("移除当前多边形失败:", e);
        }
        currentPolygon = null;
      }

      if (tempPolyline) {
        try {
          mapInstance.removeOverLay(tempPolyline);
        } catch (e) {
          console.warn("移除临时线失败:", e);
        }
        tempPolyline = null;
      }
    };

    // 动态加载天地图脚本
    const loadTdtScript = () => {
      return new Promise((resolve, reject) => {
        if (window.T) {
          resolve();
          return;
        }

        const script = document.createElement("script");
        script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${TDT_KEY}`;
        script.type = "text/javascript";

        script.onload = () => {
          console.log("天地图API加载成功");
          setTimeout(resolve, 500);
        };

        script.onerror = (error) => {
          console.error("天地图API加载失败:", error);
          reject(new Error("天地图API加载失败，请检查网络"));
        };

        document.head.appendChild(script);
      });
    };

    // 设置鼠标事件
    const setupMouseEvents = () => {
      if (!mapInstance) return;

      // 鼠标移动事件
      mapInstance.addEventListener("mousemove", (e) => {
        if (!e || !e.lnglat) return;

        // 更新鼠标位置
        mousePosition.value = {
          lat: parseFloat(e.lnglat.getLat().toFixed(6)),
          lng: parseFloat(e.lnglat.getLng().toFixed(6)),
        };

        // 在绘制模式下，更新临时线
        if (isDrawingMode.value && drawingPoints.value.length > 0) {
          updateTempPolyline(e.lnglat);
        }
      });

      // 鼠标移出事件
      mapInstance.addEventListener("mouseout", () => {
        mousePosition.value = null;
      });
    };

    // 绑定地图事件
    const bindMapEvents = () => {
      if (!mapInstance) return;

      // 缩放事件
      mapInstance.addEventListener("zoomend", () => {
        zoomLevel.value = mapInstance.getZoom();
      });

      // 移动事件
      mapInstance.addEventListener("moveend", () => {
        const center = mapInstance.getCenter();
        mapCenter.value = [center.getLng(), center.getLat()];
      });

      // 点击事件（添加顶点）
      mapInstance.addEventListener("click", (e) => {
        if (!isDrawingMode.value) return;

        // 天地图事件对象可能包装了原生事件
        const lnglat = e.lnglat || (e.event && e.event.lnglat);
        if (!lnglat) return;

        const point = {
          lng: parseFloat(lnglat.getLng().toFixed(6)),
          lat: parseFloat(lnglat.getLat().toFixed(6)),
        };

        drawingPoints.value.push(point);
        addMarker(lnglat); // 添加点标记
      });

      // 右键事件（完成绘制）
      mapInstance.addEventListener("contextmenu", (e) => {
        // 阻止默认右键菜单
        if (e && e.preventDefault) {
          try {
            e.preventDefault();
          } catch (err) {
            // 天地图事件可能没有preventDefault方法
            console.warn("无法阻止右键默认行为:", err);
          }
        }

        if (isDrawingMode.value && drawingPoints.value.length >= 3) {
          completeDrawing();
        }
      });
    };

    // 添加点标记
    const addMarker = (lnglat) => {
      try {
        // 使用自定义点标记样式，匹配Leaflet版本
        const markerIcon = new window.T.Icon({
          iconUrl:
            "",
          iconSize: new window.T.Point(12, 12),
          iconAnchor: new window.T.Point(6, 6),
        });

        const marker = new window.T.Marker(lnglat, { icon: markerIcon });
        marker.addTo(mapInstance);
        markers.push(marker);
      } catch (error) {
        console.error("添加标记失败:", error);
      }
    };

    // 更新临时线
    const updateTempPolyline = (mouseLatLng) => {
      // 清除之前的临时线
      if (tempPolyline) {
        try {
          mapInstance.removeOverLay(tempPolyline);
        } catch (e) {
          console.warn("移除临时线失败:", e);
        }
        tempPolyline = null;
      }

      if (drawingPoints.value.length === 0 || !mouseLatLng) return;

      try {
        // 创建点数组：已添加的点 + 当前鼠标位置
        const points = drawingPoints.value.map(
          (p) => new window.T.LngLat(p.lng, p.lat)
        );

        // 添加鼠标当前位置
        points.push(mouseLatLng);

        // 创建临时线
        tempPolyline = new window.T.Polyline(points, {
          color: "#1890ff",
          weight: 2,
          dashArray: "5,10",
        });
        mapInstance.addOverLay(tempPolyline);
      } catch (error) {
        console.error("绘制临时线失败:", error);
      }
    };

    // 监听缩放级别变化
    watch(zoomLevel, (newZoom) => {
      // 根据缩放级别决定显示模式
      const shouldShowFullArea = newZoom > 15;

      if (shouldShowFullArea !== showFullArea.value) {
        showFullArea.value = shouldShowFullArea;
        // 重新绘制现有虾塘
        drawExistingPonds();
      }
    });

    // 获取所有已有虾塘区域
    const fetchExistingPonds = async () => {
      try {
        // 1. 先清除之前的现有虾塘多边形和数据
        existingPolygons.forEach((polygon) => {
          try {
            mapInstance.removeOverLay(polygon);
          } catch (e) {
            console.warn("移除现有多边形失败:", e);
          }
        });
        existingPolygons = [];
        existingPonds.value = [];

        const centralResult = await getAllCentralCoordinate();

        if (centralResult.code === 0 && centralResult.data?.length) {
          for (const item of centralResult.data) {
            // 排除当前正在编辑的虾塘
            if (
              item.id &&
              props.pondId &&
              item.id.toString() === props.pondId.toString()
            ) {
              continue;
            }

            const detailResult = await getPondAddressDetailByCentral({
              central: item,
            });

            if (detailResult.code === 0 && detailResult.data) {
              let coordinates = [];
              if (typeof detailResult.data === "string") {
                coordinates = JSON.parse(detailResult.data);
              } else if (detailResult.data.coordinatesData) {
                coordinates = detailResult.data.coordinatesData;
              } else if (Array.isArray(detailResult.data)) {
                coordinates = detailResult.data;
              }

              if (Array.isArray(coordinates) && coordinates.length >= 3) {
                existingPonds.value.push({
                  id: item.id,
                  coordinates: coordinates,
                });
              }
            }
          }
          drawExistingPonds();
        }
      } catch (error) {
        console.error("获取已有虾塘区域失败:", error);
      }
    };

    // 绘制已有虾塘区域
    const drawExistingPonds = () => {
      if (!mapInstance || !window.T) return;

      // 清除现有虾塘多边形
      existingPolygons.forEach((polygon) => {
        try {
          mapInstance.removeOverLay(polygon);
        } catch (e) {
          console.warn("移除现有多边形失败:", e);
        }
      });
      existingPolygons = [];

      existingPonds.value.forEach((pond) => {
        if (!pond.coordinates || !Array.isArray(pond.coordinates)) return;

        const validCoords = pond.coordinates.filter(
          (coord) => coord && coord.lng && coord.lat
        );

        if (validCoords.length < 3) return;

        try {
          if (showFullArea.value) {
            // 显示完整多边形区域
            const path = validCoords.map(
              (coord) => new window.T.LngLat(coord.lng, coord.lat)
            );

            const polygon = new window.T.Polygon(path, {
              color: "#f56c6c",
              weight: 2,
              fillColor: "#f56c6c",
              fillOpacity: 0.2,
            });
            polygon.pondId = pond.id;
            mapInstance.addOverLay(polygon);
            existingPolygons.push(polygon);
          } else {
            // 显示中心点标记
            const centerPoint = calculateCenterPoint(validCoords);
            addPondCenterMarker(centerPoint, pond.id);
          }
        } catch (error) {
          console.error(`绘制虾塘区域失败:`, error);
        }
      });
    };

    // 虾塘中心点标记方法
    const addPondCenterMarker = (centerPoint, pondId) => {
      try {
        // 使用新的图标链接
        const markerIcon = new window.T.Icon({
          iconUrl: "https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
          iconSize: new window.T.Point(20, 20),
          iconAnchor: new window.T.Point(10, 10),
        });

        const marker = new window.T.Marker(
          new window.T.LngLat(centerPoint.lng, centerPoint.lat),
          { icon: markerIcon }
        );

        // 添加点击事件，点击时缩放到该虾塘
        marker.addEventListener("click", () => {
          if (mapInstance) {
            mapInstance.centerAndZoom(
              new window.T.LngLat(centerPoint.lng, centerPoint.lat),
              17
            );
          }
        });

        marker.addTo(mapInstance);
        marker.pondId = pondId;
        existingPolygons.push(marker);
      } catch (error) {
        console.error("添加虾塘中心点标记失败:", error);
      }
    };

    // 计算中心点
    const calculateCenterPoint = (coordinates) => {
      if (!coordinates || coordinates.length === 0) return { lng: 0, lat: 0 };

      // 使用所有点的平均值计算几何中心
      const total = coordinates.reduce(
        (sum, point) => {
          sum.lng += point.lng;
          sum.lat += point.lat;
          return sum;
        },
        { lng: 0, lat: 0 }
      );

      return {
        lng: parseFloat((total.lng / coordinates.length).toFixed(6)),
        lat: parseFloat((total.lat / coordinates.length).toFixed(6)),
      };
    };

    // 切换绘制模式
    const toggleDrawingMode = () => {
      if (isDrawingMode.value) {
        exitDrawingMode();
      } else {
        startDrawingMode();
      }
    };

    // 开始绘制模式
    const startDrawingMode = () => {
      isDrawingMode.value = true;
      drawingPoints.value = [];
      isAreaOverlapping.value = false; // 重置重叠标记

      // 清除之前的临时线
      if (tempPolyline) {
        try {
          mapInstance.removeOverLay(tempPolyline);
        } catch (e) {
          console.warn("移除临时线失败:", e);
        }
        tempPolyline = null;
      }

      // 更改地图光标
      if (mapInstance) {
        try {
          mapInstance.getContainer().style.cursor = "crosshair";
        } catch (e) {
          console.warn("设置光标样式失败:", e);
        }
      }

      ElMessage.success("绘制模式已开启，点击地图添加顶点");
    };

    // 退出绘制模式
    const exitDrawingMode = () => {
      isDrawingMode.value = false;
      drawingPoints.value = [];

      // 清除临时线
      if (tempPolyline) {
        try {
          mapInstance.removeOverLay(tempPolyline);
        } catch (e) {
          console.warn("移除临时线失败:", e);
        }
        tempPolyline = null;
      }

      // 恢复光标
      if (mapInstance) {
        try {
          mapInstance.getContainer().style.cursor = "";
        } catch (e) {
          console.warn("恢复光标样式失败:", e);
        }
      }
    };

    // 完成绘制
    const completeDrawing = () => {
      if (drawingPoints.value.length < 3) {
        ElMessage.warning("至少需要3个顶点才能完成绘制");
        return;
      }

      // 清除临时线
      if (tempPolyline) {
        try {
          mapInstance.removeOverLay(tempPolyline);
        } catch (e) {
          console.warn("移除临时线失败:", e);
        }
        tempPolyline = null;
      }

      // 设置最终坐标
      areaCoords.value = [...drawingPoints.value];

      // 检查是否与已有区域重叠
      isAreaOverlapping.value = checkAreaOverlap(areaCoords.value);

      // 计算中心点
      centerPoint.value = calculateCenterPoint(areaCoords.value);

      // 绘制最终多边形（根据重叠状态改变颜色）
      try {
        const points = areaCoords.value.map(
          (p) => new window.T.LngLat(p.lng, p.lat)
        );

        // 清除之前的多边形
        if (currentPolygon) {
          mapInstance.removeOverLay(currentPolygon);
        }

        // 如果重叠，使用红色高亮显示
        const polygonColor = isAreaOverlapping.value ? "#ff4d4f" : "#1890ff";

        currentPolygon = new window.T.Polygon(points, {
          color: polygonColor,
          weight: 3,
          fillColor: polygonColor,
          fillOpacity: isAreaOverlapping.value ? 0.3 : 0.2,
        });
        mapInstance.addOverLay(currentPolygon);
      } catch (error) {
        console.error("绘制最终多边形失败:", error);
        ElMessage.error("绘制区域失败，请重试");
        return;
      }

      // 计算面积
      calculateArea();

      // 退出绘制模式
      exitDrawingMode();

      if (isAreaOverlapping.value) {
        ElMessage.warning("当前框选区域与已有虾塘区域重叠，请重新框选！");
        setTimeout(() => {
          clearDrawing();
          ElMessage.info("已自动清除重叠区域，请重新框选");
        }, 3000);
      } else {
        ElMessage.success(`区域绘制完成，共${areaCoords.value.length}个顶点`);
      }
    };

    // 检查区域是否重叠（核心算法）
    const checkAreaOverlap = (newAreaCoords) => {
      if (!existingPonds.value || existingPonds.value.length === 0) {
        return false;
      }

      // 遍历所有已有虾塘区域
      for (const pond of existingPonds.value) {
        if (!pond.coordinates || pond.coordinates.length < 3) continue;

        // 检查新区域是否与当前虾塘区域重叠
        if (polygonsIntersect(newAreaCoords, pond.coordinates)) {
          return true;
        }
      }

      return false;
    };

    // 判断两个多边形是否相交
    const polygonsIntersect = (poly1, poly2) => {
      // 检查poly1的任意边是否与poly2的任意边相交
      for (let i = 0; i < poly1.length; i++) {
        const p1a = poly1[i];
        const p1b = poly1[(i + 1) % poly1.length];

        for (let j = 0; j < poly2.length; j++) {
          const p2a = poly2[j];
          const p2b = poly2[(j + 1) % poly2.length];

          if (linesIntersect(p1a, p1b, p2a, p2b)) {
            return true;
          }
        }
      }

      // 检查poly1的任意顶点是否在poly2内部
      if (isPointInPolygon(poly1[0], poly2)) {
        return true;
      }

      // 检查poly2的任意顶点是否在poly1内部
      return isPointInPolygon(poly2[0], poly1);
    };

    // 判断两条线段是否相交
    const linesIntersect = (p1, p2, p3, p4) => {
      const ccw = (A, B, C) => {
        return (
          (C.lat - A.lat) * (B.lng - A.lng) > (B.lat - A.lat) * (C.lng - A.lng)
        );
      };

      return (
        ccw(p1, p3, p4) !== ccw(p2, p3, p4) &&
        ccw(p1, p2, p3) !== ccw(p1, p2, p4)
      );
    };

    // 判断点是否在多边形内部（射线法）
    const isPointInPolygon = (point, polygon) => {
      let inside = false;

      for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const xi = polygon[i].lng,
          yi = polygon[i].lat;
        const xj = polygon[j].lng,
          yj = polygon[j].lat;

        const intersect =
          yi > point.lat !== yj > point.lat &&
          point.lng < ((xj - xi) * (point.lat - yi)) / (yj - yi) + xi;

        if (intersect) inside = !inside;
      }

      return inside;
    };

    // 计算面积
    const calculateArea = () => {
      if (!areaCoords.value || areaCoords.value.length < 3) return;

      try {
        const points = areaCoords.value.map(
          (coord) => new window.T.LngLat(coord.lng, coord.lat)
        );

        // 使用天地图几何工具计算面积
        if (
          window.T &&
          window.T.GeometryUtil &&
          window.T.GeometryUtil.areaOfPolygon
        ) {
          areaArea.value = window.T.GeometryUtil.areaOfPolygon(points);
        } else {
          // 降级方案：使用更精确的面积计算
          areaArea.value = calculateGeodesicArea(areaCoords.value);
        }
      } catch (error) {
        console.error("计算面积失败:", error);
        areaArea.value = null;
      }
    };

    // 更精确的球面面积计算
    const calculateGeodesicArea = (coords) => {
      const earthRadius = 6378137; // 地球半径（米）
      let area = 0;
      const len = coords.length;

      for (let i = 0; i < len; i++) {
        const j = (i + 1) % len;
        const lat1 = (coords[i].lat * Math.PI) / 180;
        const lon1 = (coords[i].lng * Math.PI) / 180;
        const lat2 = (coords[j].lat * Math.PI) / 180;
        const lon2 = (coords[j].lng * Math.PI) / 180;

        area += (lon2 - lon1) * (2 + Math.sin(lat1) + Math.sin(lat2));
      }

      area = Math.abs((area * earthRadius * earthRadius) / 2);
      return area;
    };

    // 清除绘制
    const clearDrawing = () => {
      // 清除标记
      markers.forEach((marker) => {
        try {
          mapInstance.removeOverLay(marker);
        } catch (e) {
          console.warn("移除标记失败:", e);
        }
      });
      markers = [];

      // 清除多边形和临时线
      if (currentPolygon) {
        try {
          mapInstance.removeOverLay(currentPolygon);
        } catch (e) {
          console.warn("移除多边形失败:", e);
        }
        currentPolygon = null;
      }

      if (tempPolyline) {
        try {
          mapInstance.removeOverLay(tempPolyline);
        } catch (e) {
          console.warn("移除临时线失败:", e);
        }
        tempPolyline = null;
      }

      // 重置状态
      drawingPoints.value = [];
      areaCoords.value = [];
      areaArea.value = null;
      centerPoint.value = null;
      isAreaOverlapping.value = false; // 重置重叠标记
    };

    // 关闭弹窗时的清理
    const handleClose = () => {
      clearDrawing();
      emit("close");
    };

    // 保存区域经纬度
    const handleSaveArea = async () => {
      if (!validPondId.value) {
        ElMessage.error("虾塘ID无效，请选择有效的虾塘");
        emit("save-fail", "虾塘ID无效");
        return;
      }

      if (isAreaOverlapping.value) {
        ElMessage.warning("当前区域与已有虾塘重叠，无法保存！");
        emit("save-fail", "区域重叠");
        return;
      }

      if (!areaCoords.value || areaCoords.value.length < 3) {
        ElMessage.warning("请先框选有效区域（至少3个顶点）");
        emit("save-fail", "区域无效");
        return;
      }

      try {
        const formattedCoords = areaCoords.value.map((point) => ({
          lng: parseFloat(point.lng.toFixed(6)),
          lat: parseFloat(point.lat.toFixed(6)),
        }));

        const centerPoint = calculateCenterPoint(formattedCoords);
        const centerJson = JSON.stringify(centerPoint);

        const response = await savePondCoordinates(props.pondId, {
          coordinatesData: formattedCoords,
          central: centerJson,
          area: areaArea.value,
          pointCount: areaCoords.value.length,
        });

        if (response && response.code === 0) {
          ElMessage.success("区域经纬度保存成功");
          emit("save-success", response.data);
          clearDrawing();
          emit("close");
        } else {
          ElMessage.error((response && response.message) || "保存失败");
          emit("save-fail", (response && response.message) || "保存失败");
        }
      } catch (error) {
        console.error("保存区域失败:", error);
        const errorMsg = `保存失败: ${error.message || "请重试"}`;
        ElMessage.error(errorMsg);
        emit("save-fail", errorMsg);
      }
    };

    // 监听弹窗显示状态
    watch(
      () => props.visible,
      async (newVal) => {
        if (newVal) {
          await nextTick();
          setTimeout(async () => {
            try {
              if (!mapInstance) {
                await initMap();
              } else {
                // 每次显示时重新加载数据
                await fetchExistingPonds();
              }
            } catch (error) {
              console.error("地图弹窗初始化失败:", error);
              ElMessage.error("地图初始化失败，请刷新页面重试");
            }
          }, 100);
        } else {
          clearDrawing();
        }
      }
    );

    onMounted(() => {
      if (props.visible) {
        initMap();
      }
    });

    return {
      mapCenter,
      zoomLevel,
      enableScrollWheel,
      areaCoords,
      areaArea,
      centerPoint,
      mousePosition,
      isDrawingMode,
      drawingPoints,
      hasDrawingData,
      hasValidArea,
      validPondId,
      isAreaOverlapping,
      toggleDrawingMode,
      completeDrawing,
      clearDrawing,
      handleSaveArea,
      handleClose,
      showFullArea,
    };
  },
};
</script>

<style scoped>
.amap-container {
  position: relative;
  width: 100%;
  height: 600px;
}

.map-wrapper {
  width: 100%;
  height: 100%;
}

.map-container {
  width: 100%;
  height: 100%;
}

.control-panel {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 140px;
  position: absolute;
  z-index: 9999 !important;
  top: 10px;
  left: 10px;
}

.control-btn {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background-color: #fff;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 12px;
}

.control-btn.active,
.control-btn:hover {
  border-color: #1890ff;
  background-color: #1890ff;
  color: #fff;
}

.clear-btn {
  border-color: #f56c6c;
  background-color: #f56c6c;
  color: #fff;
}

.clear-btn:hover {
  border-color: #f78989;
  background-color: #f78989;
}

.save-btn {
  border-color: #1890ff;
  background-color: #1890ff;
  color: #fff;
}

.save-btn:hover {
  border-color: #40a9ff;
  background-color: #40a9ff;
}

.control-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 状态提示 */
.status-tip {
  position: absolute;
  z-index: 1000;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 12px 16px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.95);
  font-size: 14px;
  border: 1px solid #e8e8e8;
  text-align: center;
  max-width: 400px;
}

.status-tip.drawing {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

.status-tip.error {
  background-color: #fff2f0;
  border-color: #ffccc7;
  color: #ff4d4f;
  top: 120px;
}

.status-tip small {
  color: #666;
  font-size: 12px;
}

/* 缩放提示样式 */
.zoom-tip {
  position: absolute;
  z-index: 1000;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  padding: 8px 16px;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 4px;
  font-size: 12px;
  color: #d48806;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 400px;
}

.status-tip.drawing {
  top: 70px;
}

.status-tip.error {
  top: 10px;
}

.status-tip.error.has-zoom-tip {
  top: 70px;
}

/* 区域信息面板 */
.area-info {
  position: absolute;
  z-index: 1000;
  top: 70px;
  right: 10px;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 300px;
  background-color: white;
  max-height: 70vh;
  overflow-y: auto;
}

.area-info h3 {
  margin-top: 0;
  margin-bottom: 12px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  color: #2c3e50;
  font-size: 16px;
}

.info-section {
  font-size: 14px;
}

.center-point {
  margin: 8px 0;
  padding: 8px;
  background: #f6ffed;
  border-radius: 4px;
  border: 1px solid #b7eb8f;
}

.center-point .coord {
  margin: 2px 0;
  font-family: monospace;
  font-size: 12px;
  color: #389e0d;
}

.coordinates-preview {
  margin-top: 8px;
}

.coords-list {
  margin-top: 4px;
  max-height: 150px;
  overflow-y: auto;
}

.coord-item {
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  font-family: monospace;
  font-size: 12px;
}

.coord-item:last-child {
  border-bottom: none;
}

/* 鼠标位置信息 */
.mouse-position {
  position: absolute;
  z-index: 1000;
  bottom: 40px;
  left: 10px;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 4px;
  font-size: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  border: 1px solid #d9d9d9;
}

.drawing-hint {
  color: #1890ff;
  font-weight: 500;
}

:deep(.TIcon) {
  background: transparent !important;
  border: none !important;
}

:deep(.TIcon img) {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}
</style>
